import { defineStore } from 'pinia';
import treeDefault from '@/views/file-manage/json/tree-default.json';
import {
  getChildFolderList,
  getFileList,
  FileAndFolderNodeMessage,
  FileAndFolderMessage,
  FolderMessage,
  FileMessage,
} from '@/api/tree-folder';
import { FileVersion, getFileVersionList } from '@/views/file-manage/api';
import { getNodeById } from '@/views/file-manage/hooks/utils';
import { FileManageState } from './types';

const handleTreeDataToNode = (
  list: FolderMessage[] | FileMessage[]
): FileAndFolderNodeMessage[] => {
  const treeNodes: FileAndFolderNodeMessage[] = [];
  list.forEach((item) => {
    const node: FileAndFolderNodeMessage = {
      ...item,
      isFileOrFolder: 'folderId' in item ? 1 : 0,
      key: item.id,
      title: item.name,
      children: [],
    };
    treeNodes.push(node);
  });
  return treeNodes;
};

const useFileManageStore = defineStore('file-manage', {
  state: (): FileManageState => {
    return {
      uploadModal: false,
      shareModal: false,
      shareLinkInfo: [],
      enclosureModal: false,
      enclosureInfo: {},
      moveModal: false,
      versionDrawer: false,
      treeData: treeDefault,
      expandedKeys: [],
      selectedKeys: [],
      tableData: [],
      tableLoading: false,
      filterForm: {
        name: '',
      },
      renameIndex: -1,
      renameKey: -1,
      treeRenameValue: '',
      treeRenameBackup: '',
      sendMove: () => true,
      currentFolder: undefined,
      currentFile: undefined,
      currentVersion: undefined,
      fileVersionData: [],
      selectedFolder: undefined,
    };
  },
  actions: {
    setUploadModal(value: boolean) {
      this.uploadModal = value;
    },
    setShareModal(visible: boolean, link: string[]) {
      this.shareModal = visible;
      this.shareLinkInfo = link;
    },
    setEnclosureModal(visible: boolean, info: object) {
      this.enclosureModal = visible;
      this.enclosureInfo = info;
    },
    setMoveModal(value: boolean) {
      this.moveModal = value;
    },
    setVersionDrawer(value: boolean) {
      this.versionDrawer = value;
    },
    setRenameIndex(value: number) {
      this.renameIndex = value;
    },
    setRenameKey(value: number | string) {
      this.renameKey = value;
    },
    setTreeRenameValue(value: string) {
      this.treeRenameValue = value;
      this.treeRenameBackup = value;
    },
    setSendMove(
      value: (values: () => Promise<any>) => boolean | Promise<boolean>
    ) {
      this.sendMove = value;
    },
    setCurrentFolder(value: FileAndFolderNodeMessage) {
      this.currentFolder = value;
      this.getTableData(value);
      if (
        value.children === undefined ||
        (value.children && value.children.length === 0)
      )
        this.getTreeChild(value);
    },
    setCurrentFIle(value: FileMessage) {
      this.currentFile = value;
    },
    setCurrentVersion(value: FileVersion) {
      this.currentVersion = value;
    },
    setSelectedKeys(value: (string | number)[]) {
      this.selectedKeys = value;
    },
    setSelectedFolder(value: FolderMessage) {
      this.selectedFolder = value;
    },
    async getFileVersionData() {
      const { data } = await getFileVersionList(this.currentFile?.id);
      this.fileVersionData = data.list;
    },
    initTreeData(value: string) {
      this.treeData.forEach((item) => {
        item.projectId = value;
      });
    },
    async getTreeChild(nodeData: FileAndFolderNodeMessage, selected = true) {
      const { data } = await getChildFolderList(
        nodeData.projectId,
        nodeData.teamId,
        nodeData.type,
        nodeData.id
      );
      const treeNodeData =
        'key' in nodeData
          ? nodeData
          : getNodeById(this.treeData, nodeData.id || '');
      if (treeNodeData) {
        treeNodeData.children = handleTreeDataToNode(data.list);
        this.expandedKeys.push(treeNodeData.id || treeNodeData.key || '');
      }
      if (selected) this.selectedKeys = [nodeData.id || nodeData.key || ''];
    },

    async getTableData(nodeData: FileAndFolderNodeMessage, isLoading = true) {
      if (isLoading) this.tableLoading = true;
      const promiseList = [
        await getChildFolderList(
          nodeData.projectId,
          nodeData.teamId,
          nodeData.type,
          nodeData.id
        ),
        await getFileList(nodeData.id),
      ];
      const res = await Promise.all(promiseList);
      const newTableData: FileAndFolderMessage[] = [];
      res.forEach((item, index) => {
        item?.data.list.forEach((itm) => {
          // 赋值isFileOrFolder
          const dataItem: FileAndFolderMessage = {
            ...itm,
            isFileOrFolder: index,
          };
          newTableData.push(dataItem);
          // 更新currentFile
          if (itm.id === this.currentFile?.id) {
            this.currentFile = itm;
          }
        });
      });
      this.tableData = newTableData;
      if (isLoading) this.tableLoading = false;
    },
  },
});

export default useFileManageStore;
